import { MessageSquare } from "lucide-react";

function MessageList({ messages, currentUserId, typingNames, listEndRef, loading }) {
  if (loading) return <MessagesSkeleton />;

  return (
    <div className="scroll-thin flex-1 overflow-y-auto py-2">
      {messages.length === 0 ? (
        <div className="h-full flex flex-col items-center justify-center gap-3 text-center px-6">
          <div className="w-14 h-14 rounded-full bg-surface border border-line inline-flex items-center justify-center text-fg-tertiary">
            <MessageSquare size={22} strokeWidth={1.75} />
          </div>
          <div className="text-fg text-sm font-medium">No messages yet</div>
          <div className="text-fg-tertiary text-[12px] font-mono">
            Say hi to start the conversation.
          </div>
        </div>
      ) : (
        <>
          <div className="flex items-center gap-3 px-6 pt-3.5 pb-1.5">
            <div className="flex-1 h-px bg-line-subtle" />
            <span className="text-[10px] text-fg-tertiary font-mono tracking-[0.08em] uppercase">
              Today
            </span>
            <div className="flex-1 h-px bg-line-subtle" />
          </div>
          {messages.map((m, i) => {
            const prev = messages[i - 1];
            const next = messages[i + 1];
            const sameAsPrev = prev && prev.senderId === m.senderId;
            const sameAsNext = next && next.senderId === m.senderId;
            return (
              <MessageBubble
                key={m.id}
                msg={m}
                me={currentUserId}
                groupTop={!sameAsPrev}
                groupBottom={!sameAsNext}
              />
            );
          })}
        </>
      )}

      {typingNames.length > 0 && (
        <div className="flex items-end gap-2.5 px-4 pt-1 pb-3">
          <div className="flex items-center">
            {typingNames.slice(0, 3).map((name, i) => (
              <div
                key={name}
                className="rounded-full ring-2 ring-base"
                style={{ marginLeft: i > 0 ? -8 : 0, zIndex: 10 - i }}
              >
                <Avatar name={name} size={26} />
              </div>
            ))}
            {typingNames.length > 3 && (
              <span className="ml-1.5 text-[11px] font-mono text-fg-tertiary">
                +{typingNames.length - 3}
              </span>
            )}
          </div>
          <div className="inline-flex items-center gap-1 px-3 py-2.5 bg-surface border border-line rounded-[14px]">
            {[0, 1, 2].map((i) => (
              <span
                key={i}
                className="w-[5px] h-[5px] rounded-full bg-fg-tertiary"
                style={{ animation: `flux-typing 1.2s ${i * 0.15}s infinite` }}
              />
            ))}
          </div>
        </div>
      )}

      <div ref={listEndRef} />
    </div>
  );
}

window.MessageList = MessageList;
